
#include "StringSplitter.h"

//----------------------
//--- StringSplitter ---
//----------------------

using namespace ttg::strings;

StringSplitter::StringSplitter()
{
	for (int i = 0; i < 256; i++)
	{
		isSplitter[i] = false;
		isVisible[i] = false;
	}
	raw = NULL;
}

void StringSplitter::setSplitter(char key, bool isVisible)
{
	this->isSplitter[(unsigned char)key] = true;
	this->isVisible[(unsigned char)key] = isVisible;
}

void StringSplitter::setString(const char *value)
{
	if (value != NULL)
	{
		if (raw != NULL)
		{
			lexems.clear();
			SAFE_DELETE(raw);
		}
		size_t size = strlen(value);
		raw = new char[size * 2 + 1];
		lexems.push_back(raw);
		int j = 0;
		for (size_t i = 0; i < size; i++)
			if (isSplitter[(unsigned char)value[i]])
			{
				if (j > 0 && raw[j - 1] != '\0')
				{
					raw[j++] = '\0';
					lexems.push_back(raw + j);
				}
				if (isVisible[(unsigned char)value[i]])
				{
					raw[j++] = value[i];
					raw[j++] = '\0';
					lexems.push_back(raw + j);
				}
			}
			else
				raw[j++] = value[i];
		raw[j++] = '\0';
		while (lexems.size() > 1)
			if (strlen(lexems[lexems.size() - 1]) == 0)
				lexems.pop_back();
			else
				break;
	}
}

std::string StringSplitter::join(const char *separator)
{
	std::string res;
	res.reserve(256);
	if (this->getCount() != 0)
	{
		res = getSubString(0);
		for (size_t i = 1; i < this->getCount(); i++)
		{
			res += std::string(separator);
			res += std::string(getSubString(i));
		}
	}
	return res;
}

StringSplitter::~StringSplitter()
{
	if (raw != NULL)
		delete raw;
}
